<template>
  <view class="container">
    <view class="header">
      <text class="title">发票抬头信息</text>
    </view>

    <form @submit="handleSubmit">
      <view class="form-section">
        <view class="form-item">
          <view class="label required">发票抬头</view>
          <input
            class="input"
            type="text"
            v-model="formData.invoiceTitle"
            placeholder="请输入发票抬头"
            maxlength="200"
          />
        </view>

        <view class="form-item">
          <view class="label required">单位税号</view>
          <input
            class="input"
            type="text"
            v-model="formData.invoiceTaxNumber"
            placeholder="请输入单位税号"
            maxlength="200"
          />
        </view>

        <view class="form-item">
          <view class="label">注册地址</view>
          <input
            class="input"
            type="text"
            v-model="formData.invoiceAddress"
            placeholder="请输入注册地址（可选）"
            maxlength="200"
          />
        </view>

        <view class="form-item">
          <view class="label">注册电话</view>
          <input
            class="input"
            type="text"
            v-model="formData.invoicePhone"
            placeholder="请输入注册电话（可选）"
            maxlength="200"
          />
        </view>

        <view class="form-item">
          <view class="label">开户银行</view>
          <input
            class="input"
            type="text"
            v-model="formData.invoiceBank"
            placeholder="请输入开户银行（可选）"
            maxlength="200"
          />
        </view>

        <view class="form-item">
          <view class="label">银行账户</view>
          <input
            class="input"
            type="text"
            v-model="formData.invoiceBankAccount"
            placeholder="请输入银行账户（可选）"
            maxlength="30"
          />
        </view>

        <view class="form-item">
          <view class="label">备注</view>
          <textarea
            class="textarea"
            v-model="formData.invoiceRemark"
            maxlength="200"
          />
        </view>
      </view>

      <view class="button-group">
        <button class="btn btn-default" @tap="goBack">返回</button>
        <button
          class="btn btn-primary"
          @tap="handleSubmit"
          :disabled="submitting"
        >
          {{ submitting ? "保存中..." : "保存" }}
        </button>
      </view>
    </form>
  </view>
</template>

<script>
import { saveInvoiceInfo, getInvoiceInfo } from "@/common/api/orderList.js";

export default {
  data() {
    return {
      orderId: "",
      formData: {
        invoiceTitle: "",
        invoiceTaxNumber: "",
        invoiceAddress: "",
        invoicePhone: "",
        invoiceBank: "",
        invoiceBankAccount: "",
        invoiceRemark: "",
      },
      submitting: false,
    };
  },

  onLoad(options) {
    this.orderId = options.orderId || "";
    if (!this.orderId) {
      uni.showToast({
        title: "订单ID无效",
        icon: "none",
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }

    // 加载已有的发票信息
    this.loadInvoiceInfo();
  },

  methods: {
    // 加载发票信息
    async loadInvoiceInfo() {
      try {
        uni.showLoading({
          title: "加载中...",
        });

        const res = await getInvoiceInfo(this.orderId);

        // 处理多层响应结构
        let invoiceInfo = null;
        if (res?.data?.data?.invoiceInfo) {
          invoiceInfo = res.data.data.invoiceInfo;
        } else if (res?.data?.invoiceInfo) {
          invoiceInfo = res.data.invoiceInfo;
        } else if (res?.invoiceInfo) {
          invoiceInfo = res.invoiceInfo;
        }

        if (invoiceInfo) {
          this.formData = {
            invoiceTitle: invoiceInfo.invoiceTitle || "",
            invoiceTaxNumber: invoiceInfo.invoiceTaxNumber || "",
            invoiceAddress: invoiceInfo.invoiceAddress || "",
            invoicePhone: invoiceInfo.invoicePhone || "",
            invoiceBank: invoiceInfo.invoiceBank || "",
            invoiceBankAccount: invoiceInfo.invoiceBankAccount || "",
            invoiceRemark: invoiceInfo.invoiceRemark || "",
          };
        } else {
          if (uni.getStorageSync("invoiceInfo")) {
            this.formData = uni.getStorageSync("invoiceInfo") || {};
          }
        }
      } catch (error) {
        // 加载失败不显示错误提示，保持表单为空即可
      } finally {
        uni.hideLoading();
      }
    },

    // 表单验证
    validateForm() {
      if (!this.formData.invoiceTitle.trim()) {
        uni.showToast({
          title: "请输入发票抬头",
          icon: "none",
        });
        return false;
      }

      if (!this.formData.invoiceTaxNumber.trim()) {
        uni.showToast({
          title: "请输入单位税号",
          icon: "none",
        });
        return false;
      }

      // 验证税号格式（放宽验证规则，允许中文、数字、字母）
      const taxNumber = this.formData.invoiceTaxNumber.trim();
      if (taxNumber.length < 8 || taxNumber.length > 30) {
        uni.showToast({
          title: "税号长度应在8-30位之间",
          icon: "none",
        });
        return false;
      }

      return true;
    },

    // 提交表单
    async handleSubmit() {
      if (!this.validateForm()) {
        return;
      }

      if (this.submitting) {
        return;
      }

      this.submitting = true;

      try {
        uni.showLoading({
          title: "保存中...",
        });

        const res = await saveInvoiceInfo(this.orderId, this.formData);
        uni.setStorageSync("invoiceInfo", this.formData);

        if (res.data && res.data.ok) {
          uni.hideLoading(); // 先隐藏loading
          uni.showToast({
            title: "保存成功",
            icon: "success",
          });

          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.hideLoading(); // 先隐藏loading
          const errorMsg = res?.data?.message || "保存失败";
          uni.showToast({
            title: errorMsg,
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading(); // 确保隐藏loading

        let errorMessage = "保存失败，请重试";
        if (error.response) {
          errorMessage = error.response.data?.message || errorMessage;
        } else if (error.message) {
          errorMessage = error.message;
        }

        uni.showToast({
          title: errorMessage,
          icon: "none",
        });
      } finally {
        this.submitting = false;
        // 不在这里调用hideLoading，避免重复调用
      }
    },

    // 返回
    goBack() {
      uni.navigateBack();
    },
  },
};
</script>

<style lang="scss">
.container {
  padding: 20upx;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  text-align: center;
  margin-bottom: 40upx;
}

.title {
  font-size: 36upx;
  font-weight: 600;
  color: #333;
}

.form-section {
  background-color: #fff;
  border-radius: 12upx;
  padding: 30upx;
  margin-bottom: 40upx;
}

.form-item {
  margin-bottom: 30upx;

  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-size: 28upx;
  color: #333;
  margin-bottom: 15upx;
  display: block;

  &.required::after {
    content: "*";
    color: #ff4757;
    margin-left: 5upx;
  }
}

.input,
.textarea {
  width: 100%;
  padding: 20upx;
  border: 2upx solid #e1e1e1;
  border-radius: 8upx;
  font-size: 28upx;
  color: #333;
  box-sizing: border-box;
  line-height: 1.5;
  min-height: 68upx;

  &:focus {
    border-color: #007aff;
  }
}

.textarea {
  height: 120upx;
  resize: none;
}

.button-group {
  display: flex;
  gap: 20upx;
  padding: 0 20upx;
}

.btn {
  flex: 1;
  height: 80upx;
  border-radius: 40upx;
  font-size: 32upx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;

  &.btn-default {
    background-color: #f8f8f8;
    color: #666;
  }

  &.btn-primary {
    background-color: #007aff;
    color: #fff;

    &:disabled {
      background-color: #ccc;
      color: #999;
    }
  }
}
</style>
